package com.kandy.smart.trace.web.filter;

import com.kandy.smart.trace.TraceContext;
import com.kandy.smart.trace.TraceThread;
import com.kandy.smart.trace.utils.IPUtil;
import com.kandy.smart.trace.utils.IdGenUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 调用链日志拦截器
 *
 * order -1
 * @author kandy
 */
public class TraceInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(TraceInterceptor.class);

    /**
     * 拦截处理，返回false
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        // 获取Trace对象
        TraceContext traceContext = TraceThread.getTraceThreadData(Thread.currentThread());

        if (null != traceContext && !StringUtils.isBlank(traceContext.getTraceId())){
            // 调用链,非根节点(目前不存在,不收集http间调用链信息)
        }else {
            // 调用链,根节点
//            traceThreadData.setThreadId(IdGenUtil.getRandomGen4());
            traceContext.setThreadId(String.valueOf(Thread.currentThread().getId()));
            traceContext.setTraceId(UUID.randomUUID().toString().replaceAll("-","").toLowerCase());
            traceContext.setParentId("root");
            traceContext.setAppId(IdGenUtil.getRandomGen6());
            traceContext.setLocalIp(IPUtil.getLocalHostIp());

            TraceThread.set(Thread.currentThread(),traceContext);
        }

        // 设置日志
        MDC.put("ThreadID",traceContext.getThreadId());
        MDC.put("TraceID",traceContext.getTraceId());
        MDC.put("ParentID",traceContext.getParentId());
        MDC.put("APPID",traceContext.getAppId());
        MDC.put("LocalIp",traceContext.getLocalIp());

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除当前线程对象
        TraceThread.set(Thread.currentThread(),null);

        // 删除MDC 日志设置
        MDC.remove("ThreadID");
        MDC.remove("TraceID");
        MDC.remove("ParentID");
        MDC.remove("APPID");
        MDC.remove("LocalIp");
    }
}
